<template>
  <div>
    <!-- 工位管理 -->
    <div class="topBtn">
      <div class="sizeBig"><span>工位设置</span></div>
      <div>
        <el-button type="primary" @click="changeLog">
          <i class="icon-stationLog"></i> 工位变更日志
        </el-button>
        <el-button type="primary" @click="exportExcel">
          <i class="iconfont icon-icon-"></i> 导出
        </el-button>
        <el-button type="primary" @click="forbidden">
          <i class="icon-close"></i>禁用</el-button>
        <el-button type="primary" @click="Enable">
          <i class="icon-qiy"></i>启用</el-button>
        <el-button type="primary"  @click.native="add" >
          <i class="iconfont icon-addNew"></i> 新增
        </el-button>
        <el-button type="primary" @click="edit" icon="el-icon-edit">修改</el-button>
        <el-button type="primary" @click="remove" icon="el-icon-delete">删除</el-button>
      </div>
    </div>
    <div class="message">
      <p class="character">
        生产工序的具体化，对应的是现实中的岗位操作台，工位管理是系统流程管控与员工作业操作的交互呈现，有了基础的工位信息每一个站点才能实现生成管控。
        <span class="skip">查看帮助文档</span>
      </p>
    </div>
    <div class="inputcontent">
      <el-input v-model="search" placeholder="请输入内容" class="inSearch" @keydown.native.enter="init"></el-input>
      <!-- <el-select v-model="value" placeholder="请选择">
                <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                </el-option>
      </el-select>-->
      <div class="iconSearch"></div>
    </div>

    <!-- 表格 -->
    <div class="tablesize">
      <Table :reset="reset" v-on:getId="getListId" id="out-table" v-on:changeData="changedata"></Table>
    </div>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10,20,50,100]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="TotalNum">
      </el-pagination>
    </div>

    <!-- 新增弹出框 -->
    <el-dialog
      title="新增数据"
      :visible.sync="addDialogVisible"
      width="600px">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="formName"
        label-width="140px"
        class="demo-ruleForm">
        <el-form-item label="工位名称：" prop="name">
          <el-input v-model="ruleForm.name" style="width:350px"></el-input>
        </el-form-item>
        <el-form-item label="工位描述：" prop="description">
          <el-input v-model="ruleForm.description	" style="width:350px"></el-input>
        </el-form-item>
        <el-form-item label="IP地址：" prop="ipAddress">
          <el-input v-model="ruleForm.ipAddress" style="width:350px"></el-input>
        </el-form-item>
        <el-form-item label="工位类型：" prop="stationType">
          <!-- <el-input v-model="ruleForm.stationType" style="width:350px"></el-input> -->
          <el-select v-model="ruleForm.stationType" placeholder="请选择工位类型" style="width:350px">
            <el-option 
            v-for="(item,index) in options"
            :key="index"
            :label="item.label" 
            :value="item.value"
            ></el-option>
          </el-select>  
        </el-form-item>
        <el-form-item label="线体ID：" prop="lineID">
          <!-- <el-input v-model="ruleForm.lineID" style="width:350px"></el-input> -->
          <el-select v-model="ruleForm.lineID" placeholder="请选择线体ID" style="width:350px">
            <el-option 
            v-for="(item,index) in lineList"
            :key="index"
            :label="item.LineId +'  '+ item.Name " 
            :value="item.LineId"
            ></el-option>
          </el-select>   
        </el-form-item>
        <el-form-item label="工序ID：" prop="techID">
          <!-- <el-input v-model="ruleForm.techID" style="width:350px"></el-input> -->
          <el-select v-model="ruleForm.techID" placeholder="请选择工序ID" style="width:350px">
            <el-option 
            v-for="(item,index) in typeList"
            :key="index"
            :label="item.TechId  +'  '+ item.Name" 
            :value="item.TechId"
            ></el-option>
          </el-select>   
        </el-form-item>       
        <el-form-item>
          <el-button @click.native="addDialogVisible=false">关闭</el-button>
          <el-button type="primary" @click="submitForm('formName')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 修改弹出框 -->
    <el-dialog
      title="修改数据"
      :visible.sync="editDialogVisible"
      width="600px">
      <el-form
        :model="editInfo"
        :rules="rules"
        ref="editForm"
        label-width="140px"
        class="demo-ruleForm">
        <el-form-item label="工位ID：" prop="workstationId">
          <el-input v-model="editInfo.workstationId" style="width:350px" disabled></el-input>
        </el-form-item>
        <el-form-item label="工位名称：" prop="name">
          <el-input v-model="editInfo.name" style="width:350px"></el-input>
        </el-form-item>
        <el-form-item label="工位描述：" prop="description">
          <el-input v-model="editInfo.description" style="width:350px"></el-input>
        </el-form-item>
        <el-form-item label="IP地址：" prop="ipAddress">
          <el-input v-model="editInfo.ipAddress" style="width:350px"></el-input>
        </el-form-item>
        <el-form-item label="工位类型：" prop="stationType">
          <!-- <el-input v-model="editInfo.stationType" style="width:350px"></el-input>  -->
          <el-select v-model="editInfo.stationType" placeholder="请选择工位类型" style="width:350px">
            <el-option 
            v-for="(item,index) in options"
            :key="index"
            :label="item.label" 
            :value="item.value"
            ></el-option>
          </el-select>  
        </el-form-item>
        <el-form-item label="线体ID：" prop="lineID">
          <!-- <el-input v-model="editInfo.lineID" style="width:350px"></el-input> -->
          <el-select v-model="editInfo.lineID" placeholder="请选择工序类型ID" style="width:350px">
            <el-option 
            v-for="(item,index) in lineList"
            :key="index"
            :label="item.LineId+'  '+item.Name " 
            :value="item.LineId"
            ></el-option>
          </el-select>            
        </el-form-item>
        <el-form-item label="工序ID：" prop="techID">
          <!-- <el-input v-model="editInfo.techID" style="width:350px"></el-input> -->
          <el-select v-model="editInfo.techID" placeholder="请选择工序类型ID" style="width:350px">
            <el-option 
            v-for="(item,index) in typeList"
            :key="index"
            :label="item.TechId +'  '+ item.Name"
            :value="item.TechId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click.native="editDialogVisible=false">关闭</el-button>
          <el-button type="primary" @click="editSubmitForm('editForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 工序变更日志 -->
    <el-dialog  title="工位变更日志" center :visible.sync="dialogLogVisible" width="600px">
      <Table1 :logData='logData'></Table1>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange1"
          @current-change="handleCurrentChange1"
          :current-page="currentPage1"
          :page-sizes="[10,20,50,100]"
          :page-size="size1"
          layout="total, sizes, prev, pager, next, jumper"
          :total="TotalNum1">
        </el-pagination>
      </div>

      <div class="botBtn">
        <el-button class="quxiao" @click.native="dialogLogVisible=false">取消</el-button>
        <el-button class="queding" type="primary" @click="removeLogSubmit()">删除</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {getWorkStationList,insertWorkStation,updateWorkStation,removeWorkStation,startOrStopWorkStation} from '@/api/station'
import {getTechPageList,getTechLog} from "@/api/process"
import {getLineList} from "@/api/linebody"
import Table from "./components/stationTable";
import Table1 from "./components/stationLogTable";
import {delay} from '@/utils/autoSearch'
import FileSaver from "file-saver";
import XLSX from "xlsx";

export default {
  name: "station",
  components: {
    Table,
    Table1
  },
  data() {
    return {
      search: "",
      reset:[],
      options:[
        {
          value:0,
          label:'公共'
        },
        {
          value:1,
          label:'私有'
        }
      ],
      checkIds: [], //勾选的id数组
      addlist: [], //勾选传过来的数据
      logData:[], //工位变更日志数据
      typeList:[], //工序列表数据
      lineList:[], //线体列表数据
      
      TotalNum: 0, //数据总条数
      currentPage: 1, //页码
      size: 10,
      size1: 10,
      currentPage1: 1,//页码
      TotalNum1: 0,
      
      addDialogVisible: false, //新增弹出框
      editDialogVisible:false, //修改弹出框
      dialogLogVisible:false,

      ruleForm: {
        name: "",
        description:'',
        ipAddress:"",
        stationType:"",
        lineID:"",
        techID:""
      },
      editInfo: {
        workstationId:"",
        name: "",
        description:'',
        ipAddress:"",
        stationType:"",
        lineID:"",
        techID:""
      },
      rules:{
        name: [
          { required: true, message: "请输入工序名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        description: [
          { required: true, message: "请输入工序描述", trigger: "blur" },
        ],
        ipAddress: [
          { required: true, message: "请输入IP地址", trigger: "blur" },
        ],
        stationType: [
          { required: true, message: "请输入工位类型", trigger: "blur" }          
        ],
        lineID: [
          { required: true, message: "请输入线体ID", trigger: "blur" }          
        ],
        techID: [
          { required: true, message: "请输入工序ID", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    //用来监听页面变量的改变
    //监听搜索，300ms执行一次fetchData方法（去搜索）
    search() {
      delay(() => {
        this.fetchData();
      }, 300);
    }
  },
  mounted() {
    this.init();
    this.onfocus1()
    this.onfocus2()
  },
  methods:{
    // 自动搜索的方法
    async fetchData(val){
      this.init({keyName:this.search})
    },
    handleSizeChange(size){
      this.size = size
      getWorkStationList({ keyName:this.search,page:1,pageSize:this.size}).then(res => {
        if (parseInt(res.Code) === 1) {
          this.reset = res.Result.Items;
          this.TotalNum = res.Result.TotalNum
        }
      })
    },
    handleCurrentChange(currentPage){
      this.currentPage = currentPage
      getWorkStationList({ keyName:this.search,page:this.currentPage,pageSize:this.size}).then(res => {
        if (parseInt(res.Code) === 1) {
          this.reset = res.Result.Items;
          this.TotalNum = res.Result.TotalNum
        }
      })
    }, 
    //请求数据  
    init() {
      this.reset = [];
      getWorkStationList({ keyName:this.search,page:this.currentPage,pageSize:this.size}).then(res => {
        if (parseInt(res.Code) === 1) {
          this.reset = res.Result.Items;
          this.TotalNum = res.Result.TotalNum
        }
      })
      
    },
    getListId(listId) {
      this.checkIds = listId;
    },
    changedata(data) {
      this.addlist = data;
    },
    //工位变更日志
    changeLog(){
      this.dialogLogVisible = true
      getTechLog({businessType:11,page:1,pageSize:10}).then(res =>{
        if (parseInt(res.Code) === 1) {
          this.logData = res.Result.Items
          this.TotalNum1 = res.Result.TotalNum
        }
      })
    },
    handleSizeChange1(size1){
      this.size1 = size1
      getTechLog({businessType:11,page:1,pageSize:this.size1}).then(res =>{
        if (parseInt(res.Code) === 1) {
          this.logData = res.Result.Items
        }
      })
    },
    handleCurrentChange1(currentPage1){
      this.currentPage1 = currentPage1
      getTechLog({businessType:11,page:this.currentPage1,pageSize:this.size1}).then(res =>{
        if (parseInt(res.Code) === 1) {
          this.logData = res.Result.Items
        }
      })
    },
    // 导出
    exportExcel() {
      /* generate workbook object from table */
      var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
      var wb = XLSX.utils.table_to_book(
        document.querySelector("#out-table"),
        xlsxParam
      );

      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "仓库情况表.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") {
          console.log(e, wbout);
        }
      }
      return wbout;
    },

    onfocus1(){
      //获取工序列表
      getTechPageList({ keyName:'',page:1,pageSize:1000}).then(res=>{
        if(parseInt(res.Code) === 1) {
          this.typeList = res.Result.Items
        }
      })    
    },
    onfocus2(){
      //获取线体列表
      getLineList({ keyName:'',page:1,pageSize:1000}).then(res=>{
        if(parseInt(res.Code) === 1) {
          this.lineList = res.Result.Items
        }
      })
    },
    // 新增
    add() {
      this.ruleForm = {}; 
      this.addDialogVisible = true;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          insertWorkStation(this.ruleForm).then(res => {
            if (res.Code === 1) {    
              this.$message({
                type:'success',
                message:'新增成功'
              })     
              this.init();
              this.ruleForm={}
              this.addDialogVisible = false;
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 修改
    edit(){
      if(this.addlist.length !== 1){
        this.$message('请勾选一项')
      }else{
        this.editDialogVisible = true
        this.editInfo.workstationId = this.addlist[0].WorkstationId
        this.editInfo.name = this.addlist[0].Name
        this.editInfo.description = this.addlist[0].Description
        this.editInfo.ipAddress = this.addlist[0].IPAddress
        this.editInfo.stationType = this.addlist[0].StationType
        if(this.addlist[0].StationType == 0){
          this.editInfo.stationType ='公共'
        }else{
          this.editInfo.stationType ='私有'
        }
        this.editInfo.lineID = this.addlist[0].LineId
        this.editInfo.techID = this.addlist[0].TechId
      }
    },
    editSubmitForm(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.editInfo.stationType === '公共'){
            this.editInfo.stationType = 0
          }else{
            this.editInfo.stationType = 1
          }
          updateWorkStation(this.editInfo).then(res=>{
            if (parseInt(res.Code) === 1) {         
              this.$message({
                type: 'success',
                message: '修改成功'
              })
              this.editDialogVisible = false;
              this.init();
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //禁用
     forbidden() {
      if(this.checkIds.length>0){
        if(this.addlist[0].IsEnable === 0){
          this.$message('已禁用')
        }else{
          let data = { workstationId:this.checkIds[0],isEnable:0}
          startOrStopWorkStation(data).then(res=>{
            if (parseInt(res.Code) === 1) {
              this.$message({
                type: 'success',
                message: '禁用成功!'
              })
              this.init()
            }
          })  
        }    
      }else{
        this.$message('请勾选需要禁用的工位数据')
      }
    },     
    //启用
     Enable() {
      if(this.checkIds.length>0){
        if(this.addlist[0].IsEnable === 1){
          this.$message('已启用')
        }else{
          let data = { workstationId:this.checkIds[0],isEnable:1}
          startOrStopWorkStation(data).then(res=>{
            if (parseInt(res.Code) === 1) {
              this.$message({
                type: 'success',
                message: '启用成功!'
              })
              this.init()
            }
          })
        }      
      }else{
        this.$message('请勾选需要启用的工位数据')
      }
    },  

    // 删除
    remove(){
      if(this.checkIds.length>0){
        this.$confirm('此操作将永久删除选中的工位数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => { 
          let data = {workstationId:this.checkIds[0]}
          removeWorkStation(data).then(res=>{
            if(parseInt(res.Code) === 1){
              this.$message({
                type: 'success',
                message: '删除成功!' 
              }) 
              this.init()   
            } 
          })            
        }) .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });     
      }else{
        this.$message('请勾选需要删除的工位数据')
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.sizeBig{
    font-size: 16px;
}
.topBtn {
  height: 60px;
  width: 98%;
  margin: 0 auto;
  line-height: 60px;
  display: flex;
  justify-content: space-between;
  .icon-stationLog{
    display: inline-block;
    width: 12px;
    height: 12px;
    margin-bottom: 2px;
    background: url("image/biangeng .png") no-repeat;
    vertical-align: middle;    
  }
  .icon-close{
    display: inline-block;
    width: 12px;
    height: 12px;
    margin:0 3px 2px 0;
    background: url("image/jinyong.png") no-repeat;
    vertical-align: middle;
  }
  .icon-qiy{
    display: inline-block;
    width: 13px;
    height:13px;
    margin:0 3px 2px 0;
    background: url("image/qiyong.png") no-repeat;
    vertical-align: middle;
  }
}
.message {
  width: 98%;
  margin: 0 auto;
  height: 60px;
  background: rgba(255, 255, 255, 1);
  border: 1px solid rgba(238, 238, 238, 1);
  font-size: 14px;
  .character {
    margin: 20px 0 21px 20px;
    color: #999999;
    .skip {
      color: #0095ff;
      margin-left: 10px;
      cursor: pointer;
    }
  }
}
.inputcontent {
  width: 98%;
  margin: 0 auto;
  height: 80px;
  position: relative;
  padding-top: 21px;
  box-sizing: border-box;
  .iconSearch {
    position: absolute;
    left: 277px;
    top: 30px;
    width: 20px;
    height: 20px;
    background-image: url("../system/user/image/搜索.png");
    background-repeat: no-repeat;
    cursor: pointer;
  }
  .inSearch {
    width: 308px;
    height: 40px;
  }
}
.tablesize {
  width: 98%;
  // height: 485px;
  margin: 0 auto;
  // border: 1px solid #eeeeee;
  #out-table{
    border: 1px solid #eeeeee;
  }
}
.block {
  text-align: right;
  margin: 28px 20px 0 0;
}
.subtitle{
  float: right;
  font-size: 16px;
  margin: 0 50px 10px 0;
}
.botBtn{
  text-align: center;
  margin-top: 20px;
  .quxiao{
    margin-right: 20px;
  }
  .queding{
    margin-left: 20px;
  }
}
</style>